package org.litu.app.controller.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.litu.app.entity.system.SysUser;
import org.litu.app.entity.system.SysUserLogin;
import org.litu.app.service.ISysUserLoginService;
import org.litu.app.service.ISysUserService;
import org.litu.base.controller.BaseFormController;
import org.litu.base.log.LtLog;
import org.litu.base.log.LtLogOperation;
import org.litu.base.log.LtLogOperationEnum;
import org.litu.core.base.ApiRes;
import org.litu.core.enums.ResultEnum;
import org.litu.core.login.PasswordUtil;
import org.litu.core.login.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * 用户管理controller
 *
 * @author yueye
 */
@RestController
@LtLog(module = "用户表")
@RequestMapping("/system/sysUser")
@Api(value = "用户表", tags = {"用户表"}, protocols = "http,https")
public class SysUserController extends BaseFormController<SysUser, ISysUserService> {

    @Autowired
    private ISysUserLoginService sysUserLoginService;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 保存
     *
     * @param entity 实体类
     * @return 保存成功或者是保存错误枚举
     */
    @PostMapping("/add")
    @LtLogOperation(operation = LtLogOperationEnum.ADD)
    @ApiOperation(value = "新增", notes = "将传入的数据，新增到数据库")
    @Override
    public ApiRes add(SysUser entity) {
        Map<String, String> params = requestParams();

        validate(entity, params);

        boolean res = service.save(nowUser(), entity, params);
        String defPwd = PasswordUtil.getDefaultPwd();

        return res ? ApiRes.ok(defPwd) : ApiRes.error(ResultEnum.SaveError);
    }

    @PostMapping("/logicDelete")
    @LtLogOperation(operationEx = "用户冻结")
    @ApiOperation(value = "冻结用户账号", notes = "冻结用户的账号信息，账号冻结后，用户将无法进行任何操作！")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true)
    public ApiRes logicDelete(@RequestParam(required = true) String id) {
        if (StringUtils.isBlank(id)) {
            return ApiRes.error(ResultEnum.ParamError, "用户ID不能为控!");
        }

        UserInfo user = nowUser();

        boolean res = service.logicDelete(user, id);
        return res ? ApiRes.ok() : ApiRes.error(ResultEnum.DeleteError);
    }


    /**
     * 修改密码
     *
     * @param newPwd 新密码
     * @param oldPwd 旧密码
     * @return 密码修改成功
     */
    @PostMapping(value = "/modifyPwd")
    @LtLogOperation(operation = LtLogOperationEnum.MODIFYPWD)
    @ApiOperation(value = "修改密码", notes = "根据旧密码，修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true),
            @ApiImplicitParam(name = "oldPwd", value = "旧密码", required = true),
    })
    public ApiRes modifyPwd(@RequestParam(required = true) String newPwd, @RequestParam(required = true) String oldPwd) {
        if (StringUtils.isAnyBlank(newPwd, oldPwd)) {
            return ApiRes.error(ResultEnum.ParamError, "密码不能为空!");
        }

        try {
            UserInfo user = nowUser();
            SysUserLogin userLogin = sysUserLoginService.getByUserId(user.getId());
            if (!userLogin.getPassword().equals(PasswordUtil.getDbPassword(userLogin.getSecretKey(), oldPwd))) {
                return ApiRes.error(ResultEnum.ParamError, "原密码不正确!");
            }

            String sKey = PasswordUtil.getSecretKey();
            userLogin.setSecretKey(sKey);
            userLogin.setPassword(PasswordUtil.getDbPassword(sKey, newPwd));
            userLogin.setChangePassTime(new Date());
            sysUserLoginService.updateById(userLogin);
            return ApiRes.ok("密码修改成功！");
        } catch (Exception e) {
            logger.error("修改用户密码错误！", e);
            return ApiRes.error();
        }
    }

    /**
     * 重置密码
     *
     * @param id 用户ID
     * @return 密码重置成功
     */
    @PostMapping(value = "/resetPwd")
    @LtLogOperation(operationEx = "重置密码")
    @ApiOperation(value = "重置密码", notes = "重置用户的密码,只有管理员才可以进行密码重置工作。")
    @ApiImplicitParam(name = "id", value = "用户的ID信息", required = true)
    public ApiRes resetPwd(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiRes.error(ResultEnum.ParamError, "用户Id不能为空!");
        }

        SysUserLogin userLogin = sysUserLoginService.getByUserId(id);
        String sKey = PasswordUtil.getSecretKey();
        userLogin.setSecretKey(sKey);
        userLogin.setPassword(PasswordUtil.getDbPassword(sKey));
        userLogin.setChangePassTime(new Date());

        boolean res = sysUserLoginService.updateById(userLogin);

        return res ? ApiRes.ok(PasswordUtil.getDefaultPwd()) : ApiRes.error(ResultEnum.UpdateError);
    }

    /**
     * 更新自己的头像
     *
     * @return
     */
    @PostMapping("/updatePhoto")
    @LtLogOperation(operationEx = "修改头像")
    @ApiOperation(value = "修改头像", notes = "更新自己的头像。")
    @ApiImplicitParam(name = "photoId", value = "修改头像", defaultValue = "")
    public ApiRes updatePhoto(@RequestParam(defaultValue = "") String photoId) {
        try {
            UserInfo user = nowUser();
            if (sysUserService.updatePhoto(user.getId(), photoId)) {
                return ApiRes.ok();
            } else {
                return ApiRes.error("修改失败!");
            }
        } catch (Exception e) {
            logger.error("修改用户头像错误！", e);
            return ApiRes.error();
        }
    }

    /**
     * 用户账号查重，防止账号重复
     *
     * @param id      当前用户的ID，在用户修改登陆账号时使用到
     * @param account 当前的账号信息
     * @return
     */
    @PostMapping("/accountCheck")
    @LtLogOperation(operationEx = "用户账号查重")
    @ApiOperation(value = "用户账号查重", notes = "用户账号查重,返回true标识存在重复。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID"),
            @ApiImplicitParam(name = "account", value = "账号信息", required = true)
    })
    public ApiRes accountCheck(@RequestParam(defaultValue = "") String id, @RequestParam(required = true) String account) {
        if (StringUtils.isBlank(account)) {
            return ApiRes.error(ResultEnum.ParamError);
        }

        boolean checkRes = sysUserService.accountCheck(id, account);
        return ApiRes.ok(checkRes);
    }
}
